package com.eyet.comeon.shake;


import com.eyet.comeon.R;
import com.eyet.comeon.data.Data;
import com.eyet.comeon.protocol.Protocol;
import com.eyet.comeon.ui.UI;

import android.app.Activity;
import android.app.Service;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

public class ShakeActivity extends Activity {
	
	private TextView tv_pop;
	private TextView tv_title_gname;
	private ImageView iv_qiaogu;
	private Handler handler;
	
	private SensorManager sensorMgr = null; 
	private Sensor sensor = null;
	private SensorEventListener lsn = null;
	//网络操作不能频繁进行，需要有暂停等待的时间
	private boolean isPause = false;
	//保存上一次 x y z 的坐标 
	private float bx; 
	private float by; 
	private float bz; 
	private long  btime;//这一次的时间 
	
	private float maxSX;
	private float maxSY;
	private float maxSZ;
	
	//阀值
	private float speedLimit = 9;
	
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shake);
        
        UI.createDialog(this, "摇动你的手机，敲打大鼓，为比赛加油！你会看到世界上，此时此刻与你一同加油助威的次数。", 1);
        
        //变量初始化
        initVal();
        //控件初始化
    	initViews();
    }
	
	
	@Override
	protected void onStart() {
		super.onStart();
		//重力感应监听
		sensorStart();
	}


	@Override
	protected void onStop() {
		super.onStop();
		//重力感觉监听取消
		sensorStop();
	}


	private void initVal(){
		bx = 0; 
		by = 0; 
		bz = 0; 
		btime = 0;//这一次的时间 
		
		maxSX = 0;
		maxSY = 0;
		maxSZ = 0;
	}
	
	private void initViews(){
		handler = new Handler();
		tv_pop = (TextView) this.findViewById(R.id.pop);
		tv_title_gname = (TextView) this.findViewById(R.id.title_gname);
		tv_title_gname.setText(Data.gname);
		iv_qiaogu = (ImageView) this.findViewById(R.id.qiaogu);
		initLisenter();
	}
	
	private void initLisenter(){
		iv_qiaogu.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) {
				sensorRestart();
			}
			
		});
		//iv_qiaogu.
	}
	

	private void sensorStart(){
		
		//正在等待回复则不再开始监听
		if(isPause)return;
		
		sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE); 
		if(sensorMgr == null)
			return;
        sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if(sensor == null)
        	return;
        
        lsn = new SensorEventListener() { 
			public void onSensorChanged(SensorEvent e) { 
				float speedX = 0;
				float speedY = 0;
				float speedZ = 0;
				float x = e.values[SensorManager.DATA_X]; 
				float y = e.values[SensorManager.DATA_Y]; 
				float z = e.values[SensorManager.DATA_Z]; 
				//在这里我们可以计算出 X Y Z的数值 下面我们就可以根据这个数值来计算摇晃的速度了 
				//我想大家应该都知道计算速度的公事 速度 = 路程/时间 
				float spacetime = System.currentTimeMillis() - btime;
				//Log.i("spacetime" , spacetime+"");
				if(spacetime >= 1){
					//X轴的速度 
					speedX = (x - bx) / spacetime; 
					//y轴的速度 
					speedY = (y - by) / spacetime; 
					//z轴的速度 
					speedZ = (z - bz) / spacetime; 
				}
				bx = x; 
				by = y; 
				bz = z; 
				btime = System.currentTimeMillis(); 
				
				if(maxSX < speedX){
					maxSX = speedX;
				}
				if(maxSY < speedY){
					maxSY = speedY;
				}
				if(maxSZ < speedZ){
					maxSZ = speedZ;
				}
				//tv_pop.setText(speedX + "::" + speedY+"::" + speedZ + "::" + speedLimit);
				//满足条件
				if(maxSX > speedLimit || maxSY > speedLimit || maxSZ > speedLimit){
					sensorRestart();
				}
			} 
			public void onAccuracyChanged(Sensor s, int accuracy) { 
			} 
		}; 
		// 注册listener，第三个参数是检测的精确度 
		sensorMgr.registerListener(lsn, sensor, SensorManager.SENSOR_DELAY_UI); 
	}
	
	private void sensorStop(){
		if (sensorMgr != null) {
			sensorMgr.unregisterListener(lsn);
			sensorMgr = null;
        }
	}
	
	
	private void sensorRestart(){
		//重新初始化变量
		initVal();
		//暂停阶段再发送消息
		if(isPause)
			return;
		//启动震动
		startVibrate(1000);
		//获取支持票数
		doPop_add();
		
			
		
	}
	
	private void startVibrate(long milliseconds) {
		Vibrator vib = (Vibrator)getSystemService(Service.VIBRATOR_SERVICE);
		vib.vibrate(milliseconds);
	}
	
	
	private void doPop_add(){
		//暂停等待网络回复
		isPause = true;
		
		new Thread(new Runnable(){
			public void run(){
				Protocol pro = new Protocol();
				boolean status = pro.Pop_addProtocol(Data.gid);
				if(status){
					handler.post(new Runnable(){
						public void run(){
							tv_pop.setText(Data.popular+"");
						}
					});
					
				}
				Log.i("isPause" , "= false");
				//多暂停1秒钟
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {	}
				//结束暂停
				isPause = false;
			}
		}).start();
	}

}
